//
//  ComposeTextView+Extension.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/20.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit
extension MJTComposeTextView {
    //  获取表情富文本对应字符串
    var emticonText: String {

        //  获取表情对应的表情文本附件
        //  在指定范围内遍历富文本的属性
        var result = ""
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (infoDic, range, _) -> Void in
//             print(infoDic)
            if let attachment = infoDic["NSAttachment"] as? MJTTextAttachment {
                //  就是文本附件[马上有对象]
                let chs = attachment.emoticon!.chs!
                result += chs
            } else {
                //  文本
                let text = self.attributedText.attributedSubstringFromRange(range).string
                result += text
            }
        }
//        print(result)
        return result
}
    func insertEmoticon(emoticon: MJTEmoticon, font: UIFont) {
        //判断点击的表情类型
        if emoticon.type == "0" {
            //textView.insertText(emoticon.chs!)
            //记录上一次的副文本
            let originalAttr = NSMutableAttributedString(attributedString: self.attributedText)
            // 1 ,根据表情图片路径名字创建一个UIImage
            let image = UIImage(named: emoticon.path!)
            //根据UIImage对象创建一个NSTextAttachment(文本附件)
            let attachtment = MJTTextAttachment()
            attachtment.image = image
            attachtment.emoticon = emoticon
            //取到字体高度
            let fontHeight = font.lineHeight
            attachtment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
            //3,根据NSTextAttachment创建一个NSAttributedString (副文本)
            let attr = NSAttributedString(attachment: attachtment)
            //获取textView的选中范围
            var range = self.selectedRange
            //替换选中的字符串
            originalAttr.replaceCharactersInRange(range, withAttributedString: attr)
            //追加副文本
//            originalAttr.appendAttributedString(attr)
            //设置副文本的字体大小
            originalAttr.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, originalAttr.length))
            //设置副文本
            self.attributedText = originalAttr
            //每次点击表情开始位置加一
            range.location += 1
            //设置选中范围长度为0
            range.length = 0
            //设置选中范围
            self.selectedRange = range
            //发送文字改变的通知
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            //自动使用代理调用方法 ? 意思是判断这个方法是否现实
            self.delegate?.textViewDidChange?(self)
        } else {
            self.insertText((emoticon.code! as NSString).emoji())
        }
    }
}
